package com.xfly.app.ui;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.utils.AllUtils;
import com.ptmall.app.utils.GlideUtil;
import com.ptmall.app.view.PullToRefreshLayout;
import com.ptmall.app.view.PullableListView;
import com.ptmall.app.view.TitleBarView;
import com.xfly.app.adapter.JhAdapter;
import com.xfly.app.adapter.KcAdapter;
import com.xfly.app.bean.CarBean;
import com.xfly.app.bean.DetilBean;
import com.xfly.app.bean.KcBean;
import com.xfly.app.bean.KcggBean;
import com.xfly.app.bean.UserBean;
import com.xfly.app.ui.dialog.KcDialog;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JhActivity extends BaseMvpActivity implements View.OnClickListener {

    PullToRefreshLayout refresh_view;
    PullableListView listview;
    TitleBarView title_bar;
    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();

    JhAdapter kcAdapter;

    List<KcBean> list = new ArrayList<>();

    int page = 1;

    LinearLayout zhlin, jglin, xllin;
    PopupWindow popupWindow;
    private View popView;
    String status = "2";

    TextView zhtext, jgtext, xltext,carnum;
    View zhline;

    String sort = "1";

    ImageView goodimg, gb;
    TextView goodprice, kcnum, shopcar_num, add,js,gm;
    TagFlowLayout id_flowlayout;
    RelativeLayout shopcar_jia, shopcar_jian;
    String specid = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_jh);
    }

    @Override
    public void initViews() {
        title_bar = findViewById(R.id.title_bar);
        refresh_view = findViewById(R.id.refresh_view);
        listview = findViewById(R.id.listview);
        zhlin = findViewById(R.id.zhlin);
        jglin = findViewById(R.id.jglin);
        xllin = findViewById(R.id.xllin);
        zhtext = findViewById(R.id.zhtext);
        zhline = findViewById(R.id.zhline);
        jgtext = findViewById(R.id.jgtext);
        xltext = findViewById(R.id.xltext);
        shopcar_jian = findViewById(R.id.shopcar_jian);
        shopcar_jia = findViewById(R.id.shopcar_jia);
        carnum = findViewById(R.id.carnum);
        js = findViewById(R.id.js);
        title_bar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });

        kcAdapter = new JhAdapter(getContext(), list);
        listview.setAdapter(kcAdapter);
        kcAdapter.setClick(new JhAdapter.Click() {
            @Override
            public void Click(int position) {
                getGooddetil(list.get(position).id);
            }

            @Override
            public void Click2(int position) {
            }
        });
        zhlin.setOnClickListener(this);
        jglin.setOnClickListener(this);
        xllin.setOnClickListener(this);
        js.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(),JhCarActivity.class));

                finish();
            }
        });
        getlist();
        clist();
    }

    @Override
    public void initEvents() {

        refresh_view.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                page = 1;
                getlist();
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                page++;
                getlist();
            }
        });
        apiDataRepository.myInfo(null, new ApiNetResponse<UserBean>() {
            @Override
            public void onSuccess(UserBean data) {
                title_bar.setText(data.getApply_name()+"的店");
            }
        });
    }

    private void getlist() {
        Map<String, String> map = new HashMap<>();
        map.put("page", page + "");
        map.put("sort", sort);
        apiDataRepository.goodlist(map, new ApiNetResponse<List<KcBean>>() {
            @Override
            public void onSuccess(List<KcBean> data) {
                if (refresh_view != null) {
                    refresh_view.refreshFinish(PullToRefreshLayout.SUCCEED);
                    refresh_view.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                }
                if (page == 1) {
                    list.clear();
                }
                list.addAll(data);
                kcAdapter.pushData(list);
            }

            @Override
            public void onFaile(String info, List<KcBean> data, Throwable throwable) {
                super.onFaile(info, data, throwable);
                if (refresh_view != null) {
                    refresh_view.refreshFinish(PullToRefreshLayout.SUCCEED);
                    refresh_view.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                    if (page == 0) {
                        list.clear();
                        kcAdapter.pushData(list);
                    }
                }
            }
        });
    }


    private void pop(DetilBean bean) {
        if (null == popupWindow) {
            if (null == popView) {
                popView = LayoutInflater.from(this).inflate(R.layout.pop_good, null);

                goodimg = popView.findViewById(R.id.goodimg);
                goodprice = popView.findViewById(R.id.goodprice);
                kcnum = popView.findViewById(R.id.kcnum);
                id_flowlayout = popView.findViewById(R.id.id_flowlayout);
                shopcar_jian = popView.findViewById(R.id.shopcar_jia);
                shopcar_jia = popView.findViewById(R.id.shopcar_jian);
                shopcar_num = popView.findViewById(R.id.shopcar_num);
                gb = popView.findViewById(R.id.gb);
                add = popView.findViewById(R.id.add);
                gm = popView.findViewById(R.id.gm);


            }
            GlideUtil.showImg(getContext(), bean.getAlbum().get(0).getFilepath(), goodimg);
            goodprice.setText(bean.getSpecs().get(0).getPrice());
            specid = bean.getSpecs().get(0).getId() + "";
            kcnum.setText("库存：" + bean.getStock());
            TagAdapter tagAdapter = new TagAdapter<DetilBean.SpecsBean>(bean.getSpecs()) {
                @Override
                public View getView(FlowLayout parent, int position, DetilBean.SpecsBean specsBeans) {
                    TextView tv = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.item_tv, id_flowlayout, false);
                    tv.setText(specsBeans.getName());
                    return tv;
                }

                @Override
                public void onSelected(int position, View view) {
                    super.onSelected(position, view);
                    goodprice.setText(bean.getSpecs().get(position).getPrice());
                    specid = bean.getSpecs().get(position).getId() + "";
                    kcnum.setText("库存：" + bean.getSpecs().get(position).getStock());
                }
            };
            id_flowlayout.setAdapter(tagAdapter);
            tagAdapter.setSelectedList(0);
            gm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    add2(specid);
                }
            });
            shopcar_jia.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    shopcar_num.setText(new BigDecimal(shopcar_num.getText().toString()).add(new BigDecimal("1")).toEngineeringString());
                }
            });

            shopcar_jian.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!shopcar_num.equals("1")) {
                        shopcar_num.setText(new BigDecimal(shopcar_num.getText().toString()).subtract(new BigDecimal("1")).toEngineeringString());
                    }
                }
            });
            gb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    popupWindow.dismiss();
                }
            });
            add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    add(specid);
                }
            });
//            View view = LayoutInflater.from(this).inflate(R.layout.personaldata_pop, null);
            popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setAnimationStyle(R.style.dialogAnim);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    AllUtils.backgroundAlpha(1.0f, getWindow());
                    popupWindow = null;
                    popView = null;
                }
            });
            //popupWindow.showAtLocation(rootView, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.jglin:
                if (sort.equals("2")) {
                    sort = "3";
                } else if (sort.equals("3")) {
                    sort = "2";
                } else {
                    sort = "2";
                }

                jgtext.setTextColor(0xffE6212A);
                xltext.setTextColor(0xff4D4D4D);
                zhtext.setTextColor(0xff4D4D4D);
                zhline.setVisibility(View.GONE);
                getlist();
                break;
            case R.id.xllin:
                if (sort.equals("4")) {
                    sort = "5";
                } else if (sort.equals("5")) {
                    sort = "4";
                } else {
                    sort = "4";
                }

                xltext.setTextColor(0xffE6212A);
                jgtext.setTextColor(0xff4D4D4D);
                zhtext.setTextColor(0xff4D4D4D);
                zhline.setVisibility(View.GONE);
                getlist();
                break;
            case R.id.zhlin:
                sort = "1";
                jgtext.setTextColor(0xff4D4D4D);
                xltext.setTextColor(0xff4D4D4D);
                zhtext.setTextColor(0xffE6212A);
                zhline.setVisibility(View.VISIBLE);
                getlist();
                break;
        }
    }

    private void getGooddetil(String id) {
        Map<String, String> map = new HashMap<>();
        map.put("goods_id", id);
        apiDataRepository.GoodDetil(map, new ApiNetResponse<DetilBean>(getContext()) {
            @Override
            public void onSuccess(DetilBean data) {
                pop(data);
            }
        });
    }

    private void add(String id) {
        Map<String, String> map = new HashMap<>();
        map.put("specs_id", id);
        map.put("mold", "2");
        apiDataRepository.add(map, new ApiNetResponse<Object>(getContext()) {
            @Override
            public void onSuccess(Object data) {
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
                clist();
            }
        });
    }
    private void add2(String id) {
        Map<String, String> map = new HashMap<>();
        map.put("specs_id", id);
        map.put("mold", "2");
        apiDataRepository.add(map, new ApiNetResponse<Object>(getContext()) {
            @Override
            public void onSuccess(Object data) {
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
                clist();
                startActivity(new Intent(getContext(),JhCarActivity.class));
                finish();
            }
        });
    }

    private void clist() {
        Map<String, String> map = new HashMap<>();
        map.put("mold", "2");
        apiDataRepository.clist(map, new ApiNetResponse<CarBean>(getContext()) {
            @Override
            public void onSuccess(CarBean data) {
                carnum.setText("共"+data.getCount()+"件，合计：￥"+data.getTotal());
            }
        });
    }


    /**
     * mFlowLayout.setAdapter(new TagAdapter<String>(mVals)
     *    {
     *        @Override
     *        public View getView(FlowLayout parent, int position, String s)
     *        {
     *            TextView tv = (TextView) mInflater.inflate(R.layout.tv,
     *                    mFlowLayout, false);
     *            tv.setText(s);
     *            return tv;
     *        }
     *    });
     *
     *    <?xml version="1.0" encoding="utf-8"?>
     * <selector xmlns:android="http://schemas.android.com/apk/res/android">
     *     <item android:color="@color/tag_select_textcolor"
     *           android:drawable="@drawable/checked_bg"
     *           android:state_checked="true"></item>
     *     <item android:drawable="@drawable/normal_bg"></item>
     * </selector>
     *
     * */


}
